package service

import (
	"book_srv/basic/appConfig"
	__ "book_srv/basic/proto"
	"book_srv/handler/models"
	"context"
	"errors"
	jwt "github.com/golangblogs/gojwt"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedBookServer
}

func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	var err error
	var u models.User

	if err = u.GetUserByAccount(appConfig.DB, in.Account); err != nil {
		return nil, errors.New("用户信息获取失败")
	}
	if u.ID == 0 {
		return nil, errors.New("该用户不存在")
	}

	if in.Password != u.Password {
		return nil, errors.New("密码错误")
	}

	newJwt := jwt.NewJWT("Token")
	claims := jwt.CustomClaims{
		ID:       u.ID,
		NickName: u.Account,
	}
	token, _ := newJwt.CreateToken(claims)

	return &__.LoginResp{
		Id:    int64(u.ID),
		Token: token,
	}, nil
}

// SayHello implements helloworld.GreeterServer
func (s *Server) AddBook(_ context.Context, in *__.AddBookReq) (*__.AddBookResp, error) {

	var err error
	var b models.Book

	if in.Title == "" {
		return nil, errors.New("图书名称不可为空")
	}

	if in.Num < 1 {
		return nil, errors.New("库存数量不可小于 1")
	}

	b.Title = in.Title
	b.TypesId = in.TypesId
	b.Num = in.Num
	if err = b.CreateBook(appConfig.DB); err != nil {
		return nil, errors.New("图入库失败")
	}

	return &__.AddBookResp{
		Id: int64(b.ID),
	}, nil
}

func (s *Server) BookList(_ context.Context, in *__.BookListReq) (*__.BookListResp, error) {
	var bs models.Book
	var bsList []*__.ListBook

	lists, err := bs.BookList(appConfig.DB, int(in.Page), int(in.PageSize),
		in.Title, in.TypesId, in.Status)

	if err != nil {
		return nil, err
	}

	for _, b := range lists {
		if b.Status == 1 {
			list := __.ListBook{
				Id:      int64(b.ID),
				Title:   b.Title,
				TypesId: b.TypesId,
				Status:  b.Status,
			}
			bsList = append(bsList, &list)
		}
	}

	return &__.BookListResp{
		List: bsList,
	}, nil
}

func (s *Server) UpdateStatus(_ context.Context, in *__.UpdateStatusReq) (*__.UpdateStatusResp, error) {
	var err error
	var b models.Book

	if err = b.GetBookById(appConfig.DB, in.Id); err != nil {
		return nil, errors.New("图书信息获取失败")
	}
	if b.ID == 0 {
		return nil, errors.New("该图书不存在")
	}

	if b.Status != 1 {
		return nil, errors.New("图书已借出，无法下架")
	}

	if err = b.UpdateStatus(appConfig.DB, in.Status); err != nil {
		return nil, errors.New("图书状态修改失败")
	}

	return &__.UpdateStatusResp{
		Id:     int64(b.ID),
		Status: b.Status,
		Mag:    "图书状态修改成功",
	}, nil
}

func (s *Server) DelBook(_ context.Context, in *__.DelBookReq) (*__.DelBookResp, error) {
	var err error
	var b models.Book

	if err = b.GetBookById(appConfig.DB, in.Id); err != nil {
		return nil, errors.New("图书信息获取失败")
	}
	if b.ID == 0 {
		return nil, errors.New("该图书不存在")
	}

	if b.Status != 3 {
		return nil, errors.New("非已下架图书不可删除")
	}

	if err = b.DelBook(appConfig.DB); err != nil {
		return nil, errors.New("下架图书删除失败")
	}

	return &__.DelBookResp{
		Mag: "图书删除成功",
	}, nil
}
